package cn.fancy.sdk.service;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import cn.fancy.sdk.service.utils.QdHttpReq;
import cn.fancy.sdk.service.utils.QdMakeLog;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;

class QdCheckStatus {
	
	private static String TAG = QdCheckStatus.class.getSimpleName();
	private static final String URL = QdUrlEnvSet.getStatusUrl();
	private static boolean isOn = false;
	private static boolean isReady = false;
	
	private static Context mContext;
	private final static int TOT = 3;
	private static int count = 2;
	private static int interval = 1000;
	private static String ret =  null;
	private static Handler handler = null;
	private static Runnable runnable = null;
	private static Map<String, String> msgParams = null;
	
	static boolean getReadyStatus()
	{
		return isReady;
	}
	
	static boolean getSwitchStatus()
	{
		return isOn;
	}
	
	static void startChecking(Context context)
	{	
		QdMakeLog.d(TAG, "Webus Switch: start asking");
		mContext = context;
		msgParams = new HashMap<>();
		String _gameid 		= QdUserInfo.output(msgParams, QdUserInfo.PARAMS_GAMEID, "gameid");
		String _platformid		= QdUserInfo.output(msgParams, QdUserInfo.PARAMS_PLATFORMID, "platformid");
		String _ditchid		 	= QdUserInfo.output(msgParams, QdUserInfo.PARAMS_DITCHID, "ditchid");
		String _key				= QdUserInfo.output(QdUserInfo.PARAMS_KEY);
		
		QdUserInfo.output(msgParams, QdUserInfo.PARAMS_VERSION, "SdkVersion");
		String sign = QdHttpReq.md5(_gameid + _platformid + _ditchid + _key);
		msgParams.put("sign", sign);
		
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
			}
		};
        runnable = new Runnable() {
            @Override
            public void run() {
                // handler自带方法实现定时
                try {
	                updateStatus();
                } catch (Exception e) {
                    e.printStackTrace();
                    QdMakeLog.e(TAG, e.toString());
                }
            }
        };
        handler.postDelayed(runnable, 0);
	}
	
	static void updateStatus()
	{
		QdMakeLog.d( TAG, "Webus Switch: make request at time " + (TOT - count) );
		
		if(QdHttpReq.isNetworkConnected(mContext) == false) {
			QdMakeLog.e(TAG, "Webus Switch: network error");
			return;
		}
		
    	if (android.os.Build.VERSION.SDK_INT > 9) {
    		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    		StrictMode.setThreadPolicy(policy);
    	}
		
		new Thread( new Runnable() {
			@Override
			public void run() {
            	try {
            		count = count - 1;
					ret = QdHttpReq.doRequest(URL, msgParams);
					QdMakeLog.d(TAG, "get result: " + ret);
					JSONObject json = new JSONObject(ret);
					String status = json.getString("status").trim();
					isOn = ( status.equals("1") ? true : false );
					isReady = true;
    				Message msg = new Message();
    				handler.sendMessage(msg);
				} catch (Exception e) {
					QdMakeLog.e(TAG, e.toString());
					if(count > 0) {
						QdMakeLog.d(TAG, "Webus Switch: previous request fail, retry at time " +  (TOT - count));
						handler.postDelayed(runnable, interval);
					} else {
						isReady = true;
					}
				}
			}
		}).start();
	}

}
